module.exports = function(app, express) {
    'use strict';
    var api = express.Router();
	var Book = require("./mongo");

    api.get('/somget', function(req, res) {
	res.send('some json');
    });
	


	
api.get('/books', function(req, res) {
    // res.json({ msg: 'hello' });
    Book.find({})
        .exec(function(err, books) {

            if (err) {
                res.send("error has occued")
            } else {
                console.log("mongooooose-from " + books);
                res.json(books)
            }
        });

});
api.post('/books', function(req, res) {
    var newBook = new Book();
    newBook.id = req.body.id;
    newBook.name = req.body.name;
    newBook.identityCode = req.body.identityCode;
    newBook.insurance = req.body.insurance;
    newBook.popover = req.body.popover;
    newBook.expired = req.body.expired;
    newBook.effective = req.body.effective;
    newBook.company = req.body.company;
    newBook.save(function(err, book) {
        if (err) {
            res.send("error has ocurred");
        } else {
            console.log(book);
            res.send(book);
        }
    });
    // res.send();
});
api.put('/books/:id', function(req, res) {
    Book.findOneAndUpdate({
            _id: req.params.id
        }, {
            $set: {
                name: req.body.name
            }
        }, {
            upsert: true
        },
        function(err, newBook) {
            if (err) {
                console.log("error has occured on puj");
            } else {
                console.log(newBook);
                res.status(204);
            }
        });
});

api.delete('/books/:id', function (req, res) {
	Book.findOneAndRemove({
		_id:req.params.id	
	},function(err,book) {
	if (err) {
	res.send('error on deleting')
	}
	else{
	console.log(book);
		res.status(204);
	}
	});
  res.send('POST request to the homepage');
});









   //  all api routes will begin with /api
    app.use('/', api);
}

